//
//  ReplyTopViewController.swift
//  Gaoloumi
//
//  Created by Jasper on 4/4/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import SVProgressHUD
import ImagePicker
import TZImagePickerController
import AVOSCloud

class ReplyTopViewController: RootViewController, ImagePickerDelegate, TZImagePickerControllerDelegate {

    @IBOutlet weak var replyTargetLabel: UILabel!
    @IBOutlet weak var replyTextView: UITextView!
    @IBOutlet weak var addButton1: UIButton!
    @IBOutlet weak var addButton2: UIButton!
    @IBOutlet weak var addButton3: UIButton!
    
    @IBOutlet weak var lineHeight: NSLayoutConstraint!
    @IBOutlet weak var contentViewHeight: NSLayoutConstraint!
    
    var imagePickerController:ImagePickerController?
    var imageArray = [UIImage]()
    
    // 外面传入
    var topic: Topic?
    var city: City?
    var mainReply: Reply?
    var louNum: Int?
    
    let contantHeight = UIScreen.main.bounds.height-64+1
    
    var selectedPhotos = [UIImage]()
    var selectedAssets = [AnyObject]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "回帖"
        lineHeight.constant = 0.5
        contentViewHeight.constant = contantHeight
        view.backgroundColor = UIColor.white
        replyTextView.placeholder = "回复: 3-1000个字"
        
        freshViews()
    }
    
    func freshViews() {
        if mainReply != nil {
            var str = ""
            if louNum == 0 {
                str = "沙发"
            } else if louNum == 1 {
                str = "板凳"
            } else {
                str = "\(louNum!+1)楼"
            }
            replyTargetLabel.text = "@ \(str)：\(mainReply!.content!)"
        } else {
            replyTargetLabel.text = "@ 楼主:\(topic!.content!)"
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        NotificationCenter.default.addObserver(self, selector: #selector(ReplyTopViewController.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ReplyTopViewController.keyboardDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self)
    }
    
    @IBAction func addClicked(_ sender: UIButton) {
        presentImagePicker()
    }
    
    func presentImagePicker() {
        
//        if self.imagePickerController == nil {
//            self.imagePickerController = ImagePickerController()
//            self.imagePickerController?.delegate = self
//            self.imagePickerController?.imageLimit = 3
//        }
//        dispatch_async(dispatch_get_main_queue(), {
//            self.presentViewController(self.imagePickerController!, animated: true, completion: nil)
//        })
        
        let imagePickerVc = TZImagePickerController(maxImagesCount: 3, delegate: self)
        
        imagePickerVc?.selectedAssets = NSMutableArray(array: selectedAssets)
        imagePickerVc?.allowPickingVideo = false
        imagePickerVc?.allowPickingOriginalPhoto = false
        
        self.present(imagePickerVc!, animated: true) {}
    }
    
    // MARK: TZImagePickerControllerDelegate
    
    private func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [AnyObject]!, isSelectOriginalPhoto: Bool) {
        selectedPhotos = photos
        selectedAssets = assets
        refreshButtons(photos)
    }
    
    private func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [AnyObject]!, isSelectOriginalPhoto: Bool, infos: [[AnyHashable: Any]]!) {
        
    }
    
    func imagePickerControllerDidCancel(_ picker: TZImagePickerController!) {
        
    }
    
    private func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingVideo coverImage: UIImage!, sourceAssets asset: AnyObject!) {
        
    }
    
    
    func refreshButtons(_ images: [UIImage]) {
        var buttonArray = [addButton1, addButton2, addButton3]
        var i = 0
        
        for image in images {
            let button = buttonArray[i]
            button?.setBackgroundImage(image, for: UIControlState())
            i+=1
        }
        
        buttonArray.removeSubrange(Range(0..<i))
        for button in buttonArray {
            button?.setBackgroundImage(UIImage(named: "sent_add"), for: UIControlState())
        }
    }
    
    @IBAction func replayClicked(_ sender: UIBarButtonItem) {
        replyTextView.resignFirstResponder()
        if replyTextView.text.isEmpty || replyTextView.text.characters.count < 3 {
            SVProgressHUD.showError(withStatus: "请输入回复内容: 3-1000")
            return
        }
        SVProgressHUD.show(withStatus: "数据提交中...")
        var fileArray = [AVFile]()
        
        for img in selectedPhotos {
//            let data = UIImagePNGRepresentation(img)
            let data = UIImageJPEGRepresentation(img, 0.7)
            let file = AVFile(data: data!)
            fileArray.append(file)
        }
        
        let reply = Reply()
        
        reply.content = replyTextView.text // trim() 剪切
        reply.contentImage = fileArray
        reply.isDelete = false
        reply.reply = mainReply
        reply.user = AVUser.current()
        reply.city = city
        reply.topic = topic
        reply.userName = AVUser.current().username
        
        reply.saveInBackground { (succed: Bool, error: Error?) in
            if succed {
                self.city?.incrementKey(kCityKeyReplyCount)
                self.city?.fetchWhenSave = true
//                self.city?.saveInBackground()
                
                self.topic?.incrementKey(kTopicKeyReplyCount)
                self.topic?.fetchWhenSave = true
//                self.topic?.saveInBackground()
                let user = AVUser.current()
                user.incrementKey(kUserKeyReplyCount)
                user.fetchWhenSave = true
                
                AVObject.saveAll(inBackground: [self.city!, self.topic!, user]) // 批量update和save
                
                self.navigationController?.popViewController(animated: true)

                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: kNotificationRefreshReplyListView), object: nil)
                
                SVProgressHUD.showSuccess(withStatus: "回复成功")
                
                self.topic?.lastReplyTime = NSDate() as Date
                self.topic?.saveInBackground()
                
            } else {
                SVProgressHUD.showError(withStatus: error?.localizedDescription)
            }
        }
    }
    
    @IBAction func tapGesture(_ sender: UITapGestureRecognizer) {
        replyTextView.resignFirstResponder()
    }
    
    // MARK: ImagePickerDelegate
    func wrapperDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
        
    }
    func doneButtonDidPress(_ imagePicker: ImagePickerController, images: [UIImage]) {
        imagePickerController?.dismiss(animated: true, completion: nil)
        imageArray = images
        refreshButtons(images)
    }
    func cancelButtonDidPress(_ imagePicker: ImagePickerController) {
        
    }
    
    
    
    
    // MARK: NSNotificationCenter
    
    func keyboardDidShow(_ noti: Notification) {
        
        let keyBordHeight = ((noti as NSNotification).userInfo![UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height
        
        contentViewHeight.constant = contantHeight+keyBordHeight
    }
    
    func keyboardDidHide(_ noti: Notification) {
        
        contentViewHeight.constant = contantHeight
    }
}
